package com.yz.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.book.entity.Order;
import com.yz.book.entity.Orderitem;
import com.yz.book.entity.Product;
import com.yz.book.entity.User;
import com.yz.book.mapper.OrderMapper;
import com.yz.book.mapper.OrderitemMapper;
import com.yz.book.mapper.ProductMapper;
import com.yz.book.service.CartService;
import com.yz.book.service.OrderService;
import com.yz.book.vo.CartItem;
import com.yz.book.vo.CartOrder;
import com.yz.book.vo.OrderVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ste
 * @since 2023-02-04 03:37:37
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    RedisTemplate<String, Object> stringObjectRedisTemplate;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderitemMapper itemMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    CartService cartService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public CartOrder getCartOrder(Integer userId, Integer[] productIds) {
        HashOperations<String, Object, Object> ops = stringObjectRedisTemplate.opsForHash();
        List<Object> allCartItems = ops.values(userId + "");

        CartOrder cartOrder = new CartOrder();
        cartOrder.setCartItems(new ArrayList<>());

        //计算总价
        BigDecimal totalPrice = new BigDecimal("0.00");
        for (Object item : allCartItems) {
            CartItem cartItem = (CartItem) item;
            for (Integer productId : productIds) {
                //只有当前项的id在productIds中时才作为计算总价的一部分
                //同时拿到要结算的cartItem
                if (cartItem.getProductId().equals(productId)) {
                    cartOrder.getCartItems().add(cartItem);
                    totalPrice = totalPrice.add(cartItem.getSumPrice());
                }
            }
        }

        cartOrder.setTotalPrice(totalPrice);

        return cartOrder;
    }

    @Override
    public void createOrder(User currentUser, Integer[] productIds, Integer addressId) {
        //获取要结算项目的详情
        CartOrder cartOrder = getCartOrder(currentUser.getId(), productIds);

        //创建一个订单出来
        //订单表Order中新增订单
        Order order = new Order();
        String orderNum = "GUOFS" + new Date().getTime();
        order.setOrderNum(orderNum);
        order.setTotalPrice(cartOrder.getTotalPrice());
        order.setUserId(currentUser.getId());
        order.setAddressId(addressId);
        order.setCreateTime(new Date());
        order.setStatus(1);  //订单状态 1.未支付  2.已支付   5.已取消

        int num = orderMapper.insert(order);
        System.out.println(num);
        System.out.println(order.getId());

        //存储订单详情
        List<CartItem> cartItems = cartOrder.getCartItems();

        for (CartItem cartItem : cartItems) {
            Orderitem item = new Orderitem();
            item.setProductId(cartItem.getProductId());
            item.setProductName(cartItem.getProductName());
            item.setProductPrice(cartItem.getProductPrice());
            item.setProductImgsrc(cartItem.getProductImgsrc());
            item.setBuyCount(cartItem.getBuyCount());
            item.setSumPrice(cartItem.getSumPrice());
            item.setOrderId(order.getId());

            itemMapper.insert(item);

            //更新商品的库存和购买量
            int updateNum = productMapper.updateBookStoreCount(cartItem.getProductId(), cartItem.getBuyCount());
            if (updateNum < 1) {
                throw new RuntimeException("库存量不足,下单失败");
            }
            productMapper.updateBuyCount(cartItem.getProductId(), cartItem.getBuyCount());

            //已经结算的图书要从购物车中清除掉
            cartService.updateItemNum(currentUser.getId(), cartItem.getProductId(), 0);

        }

        //发送一个mq消息,30分钟后消费者需要检查该订单是否已支付,未支付订单需要被取消掉
        //消息生产者
        rabbitTemplate.convertAndSend("cancleOrderNoramlExchange", "delayCancelOrder", order.getId());

        //发送消息的同时自定义消息的ttl
//        rabbitTemplate.convertAndSend("cancleOrderSNoramlExchange", "delayCancelOrder", order.getId(), new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                message.getMessageProperties().setExpiration("15000");  //配置消息的ttl
//                return message;
//            }
//        });
    }

    @Override
    public Page queryAllOrder(Integer userId, Integer currentPage, Integer pageSize) {

        Page<Order> page = new Page<>(currentPage, pageSize);

        //读取订单信息
        // Query Wrapper 组装查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");

        Page orderPage = orderMapper.selectPage(page, queryWrapper);

        //当前页的订单数据
        List<Order> orderList = orderPage.getRecords();
        List<OrderVo> orderVoList = new ArrayList<>();

        //List<Order> orderList = orderMapper.selectList(queryWrapper);
        for (Order order : orderList) {

            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getId());
            orderVo.setOrderNum(order.getOrderNum());
            orderVo.setOrderTime(order.getCreateTime());
            orderVo.setTotalPrice(order.getTotalPrice());
            orderVo.setStatus(order.getStatus());

            //查询订单项具体信息
            QueryWrapper<Orderitem> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("order_id", order.getId());

            List<Orderitem> itemList = itemMapper.selectList(itemQueryWrapper);

            //Lambda语法
            List<Orderitem> orderItemList = itemList.stream()
                    .map(item -> {
                        Orderitem orderItem = new Orderitem();

                        Product product = productMapper.selectById(item.getProductId());
                        orderItem.setProductImgsrc(product.getProductImgsrc());
                        orderItem.setProductName(item.getProductName());
                        orderItem.setBuyCount(item.getBuyCount());
                        orderItem.setSumPrice(item.getSumPrice());

                        return orderItem;
                    })
                    .collect(Collectors.toList());

            orderVo.setOrderItemList(orderItemList);

            orderVoList.add(orderVo);
        }

        orderPage.setRecords(orderVoList);


        return orderPage;
    }

    @Override
    public void updateState(Integer orderId, Integer newStatus) {

        orderMapper.updateStatus(orderId, newStatus);
    }


}
